package com.ruiao.car.service.job;

import com.ruiao.car.service.worm.IWormService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by jsonval on 2020/6/12.
 */
@Slf4j
@Component
@Configurable
@PropertySource(value = "classpath:application.yml")
@EnableScheduling
public class JobService {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10);
        return taskScheduler;
    }

    @Scheduled(cron = "${cron.worm}")
    public void worm() throws Exception {

        Map<String, IWormService> wormServiceMap = applicationContext.getBeansOfType(IWormService.class);
        Iterator<IWormService> wormServiceIterator = wormServiceMap.values().iterator();
        while (wormServiceIterator.hasNext()) {
            try {
                IWormService wormService = wormServiceIterator.next();
                wormService.handleWormData();
            } catch (Exception e) {
                log.error("自动爬虫执行{}", e.getMessage());
            }
        }
    }


}
